package cn.harry.modular.portrait.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.portrait.domain.UserSegments;
import cn.harry.modular.portrait.service.UserSegmentsService;
import cn.harry.modular.portrait.vo.PortraitUserVO;
import cn.harry.modular.portrait.vo.UserSegmentsCondition;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 用户分群前端控制层
 *
 * @author harry
 * @公众号 Harry技术
 */
@Tag(name = "用户分群接口")
@RestController
@RequestMapping("/userSegments")
@RequiredArgsConstructor
public class UserSegmentsController {

    private final UserSegmentsService userSegmentsService;

    /**
     * 分页查询列表
     */
    @Operation(summary = "分页查询")
    @PreAuthorize("@ss.hasPermission('portrait_user_segments_page')")
    @GetMapping(value = "/page")
    public R<IPage<UserSegments>> page(@ParameterObject Page<UserSegments> page, @ParameterObject UserSegments entity) {
        return R.success(userSegmentsService.page(page, Wrappers.lambdaQuery(entity)));
    }

    /**
     * 根据id获取详情
     */
    @Operation(summary = "根据id获取详情")
    @PreAuthorize("@ss.hasPermission('portrait_user_segments_get')")
    @GetMapping(value = "/{id}")
    public R<UserSegments> getById(@PathVariable Long id) {
        return R.success(userSegmentsService.getById(id));
    }

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PreAuthorize("@ss.hasPermission('portrait_user_segments_add')")
    @SysLog(title = "portrait_user_segments", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Integer> save(@RequestBody UserSegments entity) {
        return userSegmentsService.save(entity) ? R.success() : R.failed();
    }

    /**
     * 更新
     */
    @Operation(summary = "更新")
    @PreAuthorize("@ss.hasPermission('portrait_user_segments_edit')")
    @SysLog(title = "portrait_user_segments", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Integer> update(@RequestBody UserSegments entity) {
        return userSegmentsService.updateById(entity) ? R.success() : R.failed();
    }

    /**
     * 删除
     */
    @Operation(summary = "删除")
    @PreAuthorize("@ss.hasPermission('portrait_user_segments_del')")
    @SysLog(title = "portrait_user_segments", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        return userSegmentsService.removeBatchByIds(Arrays.asList(ids)) ? R.success() : R.failed();
    }

    /**
     * 人口属性： 用户性别、活跃度
     * 行为属性：近 30 日购买次数、近 30日购买金额
     * 风险控制：近 30日支付异常次数、用户信用评分、近30日异地登录次数、密码强度、近x日是否申请贷款
     */

    @Operation(summary = "计算覆盖人群数量")
    @PostMapping("/countUserSegments")
    public R<Integer> countUserSegments(@RequestBody UserSegmentsCondition condition) {
        return R.success(userSegmentsService.countUserSegments(condition));
    }

    @Operation(summary = "保存用户分群")
    @PostMapping("/saveUserSegments")
    public R<Integer> saveUserSegments(@RequestBody UserSegmentsCondition condition) {
        return userSegmentsService.saveUserSegments(condition) ? R.success() : R.failed();
    }

    /**
     * 导出
     */
    @SneakyThrows
    @Operation(summary = "导出")
    @GetMapping("/export")
    public void export(UserSegments entity, HttpServletResponse response) {
        List<PortraitUserVO> list = userSegmentsService.export(entity);

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String fileName = URLEncoder.encode("用户", StandardCharsets.UTF_8);

        response.setHeader("Content-disposition", "attachment;filename=" + fileName + "_" + DateUtil.current() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), PortraitUserVO.class).sheet("用户").doWrite(list);
    }
}
